package uvt.gui.mainframe.subpanel.addsss;

import java.awt.Color;

import javax.swing.JButton;

import org.openstreetmap.gui.jmapviewer.Coordinate;

import uvt.database.Database;
import uvt.database.InsertOperations;
import uvt.gui.mainframe.object.InfoFrame;
import uvt.gui.mainframe.object.command.Command;
import uvt.gui.mainframe.object.observer.ConcreteObservable;
import uvt.map.PositionsSettings;
import uvt.map.graph.element.Station;
import uvt.map.mapmarker.MapMarkerDot;

public class AddFirstStationButton extends JButton implements Command {
	
	private Validable validate;
	private TextFieldGetter getter;
	
	public AddFirstStationButton(Validable validate,TextFieldGetter getter) {
		super("Add First Station");
		this.validate = validate;
		this.getter = getter;
	}
	
	public void execute() {
		try {
			validate.validateForAddFirstStationButton();
			Station station = new Station();
			station.setName(getter.getStationName());
			station.setLatitude(Double.valueOf(getter.getLatitude()));
			station.setLongitude(Double.valueOf(getter.getLongitude()));
			CoordinateResources resource = CoordinateResources.getInstance();
			resource.setFirstStation(station);
			resource.setStationStart(station);
			resource.setSegmentStart(new Coordinate(station.getLatitude(),
					                                station.getLongitude())); 
			((InsertOperations)Database.getInstace()).insertRowStation(station);
			ConcreteObservable.getStationNameObservableInstance().stateChanged();
			MapMarkerDot.setDotColor(Color.white);
			PositionsSettings.getInstance().addStationOnMap(station);
			Thread t = new Thread(new Runnable() {
				public void run() {
					new InfoFrame("Information","First Station was added in database!");
			    }
			});
			t.start();
		} catch(final Exception ex) {
			Thread t = new Thread(new Runnable() {
				public void run() {
					new InfoFrame("Error",ex.getMessage());
				}
			});
			t.start();
		}
		
	}
	
}